package com.miguo.utils;

import android.content.Context;

import com.miguo.app.AppContext;
import com.miguo.bean.AdvertBean;
import com.miguo.bean.CommentBean;
import com.miguo.db.AdvertDB;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.request.RequestJsonHandler;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.mrper.ext.event.AdverLoadFinishedEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class Advert {

    private ApiPrefs prefs;

    private Context mContext;

    private boolean isVersionMark = false;

    private static Advert instance;

    private List<AdvertBean> arrayList;

    private Long getTime;
    private Long AdTime;

    private Advert(Context context, boolean isVersionMark) {
        this.mContext = context;
        this.isVersionMark = isVersionMark;
    }

    public static Advert getInstance(Context context, boolean isVersionMark) {
        if (instance == null) {
            instance = new Advert(context, isVersionMark);
        }
        return instance;
    }

    public void init() {
        prefs = AppContext.Prefs();
        getTime = DateUtils.getCurrentDateLong("yyyyMMddHH");
        AdTime = prefs.getAdvertTime();
        if (getTime > AdTime || isVersionMark) {
            getData();
        }
    }

    private void getData() {
        RequestJsonHandler callback = new RequestJsonHandler() {
            @Override
            public void onRequestFinish(JsonData json) {
                if (json.optInt("status") == 200) {
                    JsonData data = json.optJson("data");
                    arrayList = CommentBean.AdvertData(data);
                    AdvertDB.getInstance(mContext).deleteAll();
                    if (arrayList != null && arrayList.size() > 0)
                        AdvertDB.getInstance(mContext).saveList(arrayList);
                    prefs.setAdvertTime(getTime);
                    //添加时间2016-04-27 10:43,通知首页更新数据
                    EventBus.getDefault().post(new AdverLoadFinishedEvent());
                    //------  END ----------
                    //存储版本标识
                    AppContext.Prefs().setVersionMark(CommonUtils.getVersionCode(mContext));//记录当前版本号
                }
            }
        };

        HttpClient.post(Url.toRoute(Url.Ad.List, 1), callback);
    }
}
